const CACHE_VERSION = 'v1';
const CACHE_NAME = `my-cache-${CACHE_VERSION}`;

self.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open(CACHE_NAME)
           .then(function(cache) {
                return cache.addAll([]);
            })
    );
    self.skipWaiting();
});

self.addEventListener('activate', function(event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.filter(function(cacheName) {
                    return cacheName.startsWith('my-cache-') && cacheName!== CACHE_NAME;
                }).map(function(cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
    self.clients.claim();
});

// 监听推送事件
self.addEventListener('push', function(event) {
    const data = event.data ? event.data.text() : '默认消息';
    const options = {
        body: data,
        icon: 'https://autofelix.github.io/autofelix/u/favicon.ico',
        vibrate: [100, 50, 100],
        data: {
            dateOfArrival: Date.now(),
            primaryKey: '2'
        }
    };
    event.waitUntil(
        self.registration.showNotification('新消息推送', options)
    );
});

// 监听通知点击事件
self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(
        clients.openWindow('https://autofelix.blog.csdn.net/')
    );
});

// 监听来自页面的消息
self.addEventListener('message', function(event) {
    console.log('收到消息:', event.data);
    if (event.data.type === 'push') {
        const options = {
            body: event.data.data,
            icon: 'https://autofelix.github.io/autofelix/u/favicon.ico',
            vibrate: [100, 50, 100],
            data: {
                dateOfArrival: Date.now(),
                primaryKey: '2'
            }
        };
        event.waitUntil(
            self.registration.showNotification('新消息推送', options)
              .then(() => {
                    console.log('通知显示成功');
                })
              .catch((error) => {
                    console.error('通知显示失败:', error);
                })
        );
    }
});

